package com.htl.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.htl.entity.ProductCategory;
import com.htl.entity.ProductInfo;
import com.htl.exception.ShopException;
import com.htl.form.ProductEditForm;
import com.htl.form.ProductForm;
import com.htl.handler.CustomCellWriteHandler;
import com.htl.mapper.ProductCategoryMapper;
import com.htl.mapper.ProductInfoMapper;
import com.htl.result.ResponseEnum;
import com.htl.service.ProductCategoryService;
import com.htl.service.ProductInfoService;
import com.htl.util.ResultVOUtil;
import com.htl.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 类目表 前端控制器
 * </p>
 *
 * @author 韩天乐
 * @since 2021-11-13
 */

@RestController
@RequestMapping("/seller/product")
public class SellerProductController {

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;


    @GetMapping("/findAllProductCategory")
    public ResultVO findAllProductCategory(){
        List<ProductCategory> list = this.productCategoryService.list();
        List<ProductCategoryVO> voList = new ArrayList<>();
        for (ProductCategory productCategory : list) {
            ProductCategoryVO vo = new ProductCategoryVO();
            vo.setName(productCategory.getCategoryName());
            vo.setType(productCategory.getCategoryType());
            voList.add(vo);
        }
        Map<String,List> map = new HashMap<>();
        map.put("content", voList);
        return ResultVOUtil.success(map);
    }


    @PostMapping("/add")
    public ResultVO add(@Valid @RequestBody ProductForm productForm, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            throw new ShopException(ResponseEnum.PRODUCT_EMPTY.getMsg());
        }
        ProductInfo productInfo = new ProductInfo();
        BeanUtils.copyProperties(productForm, productInfo);
        productInfo.setProductStatus(1);
//        productInfo.setProductDescription(productForm.getProductDescription());
//        productInfo.setProductIcon(productForm.getProductIcon());
//        productInfo.setProductName(productForm.getProductName());
//        productInfo.setProductPrice(productForm.getProductPrice());
//        productInfo.setProductStock(productForm.getProductStock());
//        productInfo.setCategoryType(productForm.getCategoryType());
        boolean save = this.productInfoService.save(productInfo);
        if (save) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(null);
    }


    @GetMapping("/list/{page}/{size}")
    public ResultVO list(@PathVariable("page") Integer page,
                         @PathVariable("size") Integer size){
        Page<ProductInfo> page1 = new Page<>(page,size);
        Page<ProductInfo> page2 = this.productInfoService.page(page1, null);
        List<ProductInfo> records = page2.getRecords();
        ArrayList<SellerProductVO> voList = new ArrayList<>();
        for (ProductInfo record : records) {
            SellerProductVO vo = new SellerProductVO();
            BeanUtils.copyProperties(record, vo);
            if (record.getProductStatus() == 1) {
                vo.setStatus(true);
            }
            String nameByType = this.productCategoryMapper.getNameByType(record.getCategoryType());
            vo.setCategoryName(nameByType);
            voList.add(vo);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("content",voList);
        map.put("size", page2.getSize());
        map.put("total", page2.getTotal());
        return ResultVOUtil.success(map);
    }


    @GetMapping("/like/{page}/{size}/{keyWord}")
    public ResultVO like(@PathVariable("page") Integer page,
                         @PathVariable("size") Integer size,
                         @PathVariable("keyWord") String keyWord){
        Page<ProductInfo> page1 = new Page<>(page, size);
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_name", keyWord);
        Page<ProductInfo> page2 = this.productInfoService.page(page1, queryWrapper);
        List<ProductInfo> records = page2.getRecords();
        List<SellerProductVO> voList = new ArrayList<>();
        for (ProductInfo record : records) {
            SellerProductVO vo = new SellerProductVO();
            BeanUtils.copyProperties(record, vo);
            if (record.getProductStatus() == 1) {
                vo.setStatus(true);
            }
            String nameByType = this.productCategoryMapper.getNameByType(record.getCategoryType());
            vo.setCategoryName(nameByType);
            voList.add(vo);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("content", voList);
        map.put("size", page2.getSize());
        map.put("total", page2.getTotal());
        return ResultVOUtil.success(map);
    }


    @GetMapping("/findByCategory/{page}/{size}/{categoryType}")
    public ResultVO findByCategory(@PathVariable("page") Integer page,
                                   @PathVariable("size") Integer size,
                                   @PathVariable("categoryType") Integer categoryType){
        Page<ProductInfo> page1 = new Page<>(page, size);
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_type", categoryType);
        Page<ProductInfo> page2 = this.productInfoService.page(page1, queryWrapper);
        List<ProductInfo> records = page2.getRecords();
        List<SellerProductVO> voList = new ArrayList<>();
        for (ProductInfo record : records) {
            SellerProductVO vo = new SellerProductVO();
            BeanUtils.copyProperties(record, vo);
            if (record.getProductStatus() == 1) {
                vo.setStatus(true);
            }
            String nameByType = this.productCategoryMapper.getNameByType(record.getCategoryType());
            vo.setCategoryName(nameByType);
            voList.add(vo);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("content", voList);
        map.put("size", page2.getSize());
        map.put("total", page2.getTotal());
        return ResultVOUtil.success(map);
    }


    @GetMapping("/findById/{id}")
    public ResultVO findById(@PathVariable("id") Integer id){
        ProductInfo byId = this.productInfoService.getById(id);
        SellerProductVOById vo = new SellerProductVOById();
        BeanUtils.copyProperties(byId, vo);
        if (byId.getProductStatus() == 1) {
            vo.setStatus(true);
        }
        Map<String,Integer> map = new HashMap<>();
        map.put("categoryType", byId.getCategoryType());
        vo.setCategory(map);
        return ResultVOUtil.success(vo);
    }


    @DeleteMapping("/delete/{id}")
    public ResultVO delete(@PathVariable("id") Integer id){
        boolean b = this.productInfoService.removeById(id);
        if (b) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(null);
    }


    @PutMapping("/updateStatus/{id}/{status}")
    public ResultVO updateStatus(@PathVariable("id") Integer id,
                                 @PathVariable("status") Boolean status){
        Integer statusInt = 0;
        if(status) statusInt = 1;
        Boolean aBoolean = this.productInfoMapper.updateStatusById(id, statusInt);
        if(aBoolean) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(null);
    }


    @PutMapping("/update")
    public ResultVO update(@Valid @RequestBody ProductEditForm productEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new ShopException(ResponseEnum.PRODUCT_EMPTY.getMsg());
        }
        ProductInfo productInfo = new ProductInfo();
        BeanUtils.copyProperties(productEditForm, productInfo);
        productInfo.setProductStatus(0);
        if(productEditForm.getStatus()) productInfo.setProductStatus(1);
        productInfo.setCategoryType(productEditForm.getCategory().getCategoryType());
        boolean b = this.productInfoService.updateById(productInfo);
        if(b) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(null);
    }


    @GetMapping("/export")
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("商品信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<ProductExcelVO> productExcelVOList = this.productInfoService.productExcelVOList();
            EasyExcel.write(response.getOutputStream(), ProductExcelVO.class)
                    .registerWriteHandler(new CustomCellWriteHandler())
                    .sheet("商品信息")
                    .doWrite(productExcelVOList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/import")
    public ResultVO importData(@RequestParam("file") MultipartFile file){
        List<ProductInfo> productInfoList = null;
        try {
            productInfoList = this.productInfoService.excelToProductInfoList(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(productInfoList==null){
            return ResultVOUtil.fail("导入Excel失败！");
        }
        boolean result = this.productInfoService.saveBatch(productInfoList);
        if(result)return ResultVOUtil.success(null);
        return ResultVOUtil.fail("导入Excel失败！");
    }

}

